//
//  UserAccountViewModel.swift
//  Webo10
//
//  Created by ChengXiwu on 2017/7/30.
//  Copyright © 2017年 ChengXiwu. All rights reserved.
//

import Foundation

class UserAccountViewModel {
    
    static let userAccount = UserAccountViewModel()    
    
    var account: UserAccount?
    
    // 返回有效的token
    var accessToken: String?{
        if !isExpired {
            return account?.access_token
        }
        return nil
    }
    
    var userIsLogon: Bool{
        return account?.access_token != nil && !isExpired
    }
    
    var avatarUrl: URL{
        return URL(string: account?.avatar_large ?? "wrong_url")!
    }
        
    // 判断token是否过期
    private var isExpired: Bool{        
        if account?.expiresDate?.compare(Date()) == ComparisonResult.orderedDescending {
            return false
        }
        return true
    }
    
    // 构造函数
    private init() {
        // 从沙盒解档数据,恢复当前数据
        account = NSKeyedUnarchiver.unarchiveObject(withFile: ARCHIVE_PATH) as? UserAccount
        // 如果过期则清空token
        if isExpired {
            logPrint("token已过期")
            account = nil
        }
        
        logPrint(account?.description ?? "account无效")
        
    }
    
}
